package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//通过userDao完成 对 user 表的操作 ;
public class UserDao {
    //新增用户, 博客系统的功能暂时没有 新增功能 ;
    // 删除用户, 也没有删除用户,

    // 1. 根据用户 Id ,查询到用户信息
    public User getUserById(int userId){
        Connection connection = null ;
        PreparedStatement statement = null ;
        ResultSet resultSet = null ;
        try{
            connection = DBUtil.getConnection();
            String sql = "select * from user where userId=?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
              User user = new User();
              user.setUserId(userId);
              user.setUserName(resultSet.getString("userName"));
              user.setPassword(resultSet.getString("password"));
              return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(connection,statement,resultSet);
        }

        return null ;
    }

    //2. 根据用户名,来查询对应用户信息 ;
    public User getUserByName(String userName){
        Connection connection = null ;
        PreparedStatement statement = null ;
        ResultSet resultSet = null ;
        try{
            connection = DBUtil.getConnection();
            String sql = "select * from user where userName=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, userName);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setUserName(userName);
                user.setPassword(resultSet.getString("password"));
                user.setUserId(resultSet.getInt("userId"));
                return user;
            }
        } catch (SQLException e) {
           e.printStackTrace();
         }finally{
            DBUtil.close(connection,statement,resultSet);
        }
        return null ;
    }


}
